import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    user: null,
    token: localStorage.getItem('token') || '',
    systemInfo: null,
    sidebarCollapsed: false
  },
  
  mutations: {
    SET_TOKEN(state, token) {
      state.token = token
      localStorage.setItem('token', token)
    },
    CLEAR_TOKEN(state) {
      state.token = ''
      localStorage.removeItem('token')
    },
    SET_USER(state, user) {
      state.user = user
    },
    SET_SYSTEM_INFO(state, info) {
      state.systemInfo = info
    },
    TOGGLE_SIDEBAR(state) {
      state.sidebarCollapsed = !state.sidebarCollapsed
    }
  },
  
  actions: {
    // 登录
    login({ commit }, credentials) {
      return new Promise((resolve, reject) => {
        axios.post('/auth/login', credentials)
          .then(response => {
            const { token, user } = response.data
            commit('SET_TOKEN', token)
            commit('SET_USER', user)
            resolve(response)
          })
          .catch(error => {
            reject(error)
          })
      })
    },
    
    // 注销
    logout({ commit }) {
      commit('CLEAR_TOKEN')
      commit('SET_USER', null)
    },
    
    // 获取用户信息
    getUserInfo({ commit }) {
      return new Promise((resolve, reject) => {
        axios.get('/auth/profile')
          .then(response => {
            commit('SET_USER', response.data)
            resolve(response)
          })
          .catch(error => {
            reject(error)
          })
      })
    },
    
    // 获取系统信息
    getSystemInfo({ commit }) {
      return new Promise((resolve, reject) => {
        axios.get('/system/info')
          .then(response => {
            commit('SET_SYSTEM_INFO', response.data)
            resolve(response)
          })
          .catch(error => {
            reject(error)
          })
      })
    }
  },
  
  getters: {
    isAuthenticated: state => !!state.token,
    isAdmin: state => state.user && state.user.role === 'admin',
    username: state => state.user ? state.user.username : '',
    userPermissions: state => state.user ? state.user.permissions : {},
    sidebarStatus: state => state.sidebarCollapsed
  }
})

export default store 